package com.zq.learn.springbatch.combination.quartz;

import com.zq.learn.springbatch.combination.batch.OrderTask;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.quartz.CronScheduleBuilder.cronSchedule;

/**
 * QuartzTasks
 *
 * @author ZhangQi
 * @date 2020/2/19
 */
public class QuartzTasks {
  Logger logger = LoggerFactory.getLogger(QuartzTasks.class);

  private MongoTemplate mongoTemplate;
  private Scheduler scheduler;

  /**
   * 构造函数，注入有Spring管理的Mongo操作模板和任务容器
   *
   * @param mongoTemplate Mongo操作模板
   * @param scheduler     任务容器
   */
  public QuartzTasks(MongoTemplate mongoTemplate, Scheduler scheduler) {
    this.mongoTemplate = mongoTemplate;
    this.scheduler = scheduler;
  }

  /**
   * 统计订单操作
   */
  public void statisticOrder() {
    //查出订单生成日期，并去重，返回结果如：[{_id=20200218}, {_id=20200213}]
    List<AggregationOperation> operations = new ArrayList<>();
    operations
      .add(Aggregation.project("timestamp").and("timestamp").project("substr", 0, 8).as("day"));
    operations.add(Aggregation.group("day"));
    Aggregation aggregation = Aggregation.newAggregation(operations);
    AggregationResults<Map> sourcedata =
      mongoTemplate.aggregate(aggregation, "SourceData", Map.class);
    List<Map> dayList = sourcedata.getMappedResults();
    logger.info(dayList.toString());
    //遍历订单生成日期，按每个日期创建对应的JobDetail和Trigger(Quartz)，并绑定关系
    for (Map dayMap : dayList) {
      String day = dayMap.get("_id").toString();
      JobDetail jobDetail =
        JobBuilder.newJob(OrderTask.class) //载入Job（Quartz）实现类
          .withIdentity("OrderTask_" + day)
          .usingJobData("day", day) //加入日期参数
          .build();
      CronTrigger trigger =
        TriggerBuilder.newTrigger().forJob(jobDetail).withIdentity("OrderTrigger_" + day)
          .withSchedule(cronSchedule("*/10 * * * * ?")).build();
      try {
        scheduler.scheduleJob(jobDetail, trigger);
      } catch (SchedulerException e) {
        e.printStackTrace();
      }
    }
  }

}
